{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "94448237",
   "metadata": {},
   "source": [
    "# DeepSeek Agent 实战：小红书爆款文案生成助手\n",
    "\n",
    "本 Notebook 将指导您如何使用 DeepSeek LLM 构建一个能够生成小红书爆款文案的智能 Agent。我们将从需求拆解开始，逐步定义 Agent 的系统提示词 (System Prompt)、外部工具 (Tools)，并实现其核心的工作流程，最终生成符合小红书平台特点的文案。\n",
    "\n",
    "## 1. 环境准备与DeepSeek API配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "71f935e0",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "1wW109tW7o_B",
    "outputId": "33918a20-f56f-4a0b-d24c-d40b90e0c036"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "# 建议将 API Key 设置为环境变量，避免直接暴露在代码中\n",
    "# 从环境变量获取 DeepSeek API Key\n",
    "api_key = os.getenv(\"DEEPSEEK_API_KEY\")\n",
    "if not api_key:\n",
    "    raise ValueError(\"请设置 DEEPSEEK_API_KEY 环境变量\")\n",
    "\n",
    "# 初始化 DeepSeek 客户端\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=api_key,\n",
    "    base_url=\"https://api.deepseek.com/v1\",  # DeepSeek API 的基地址\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8342756e",
   "metadata": {},
   "source": [
    "## 2. 需求拆解与Agent任务规划\n",
    "\n",
    "#### 用户痛点与核心需求：\n",
    "*   **效率低下：** 人工创作周期长，难以满足高频发布需求。\n",
    "*   **创意瓶颈：** 难以持续产出新颖、吸引人的爆款创意。\n",
    "*   **趋势捕捉难：** 实时流行元素难以快速融入文案。\n",
    "*   **平台特性把握：** 小红书特有风格（标题、正文、标签、表情）难以精准复制。\n",
    "\n",
    "#### “爆款”文案的特征：\n",
    "*   **强吸引力标题：** 制造好奇、痛点共鸣、利益点清晰。\n",
    "*   **沉浸式正文：** 真实体验分享、细节描述、情感共鸣。\n",
    "*   **精准且多样标签：** 热门话题、品牌词、产品词、垂直领域词。\n",
    "*   **生动表情符号：** 增强表达力，提升活泼感。\n",
    "*   **清晰的行动召唤 (CTA)。**\n",
    "\n",
    "#### Agent 任务规划：核心工作流\n",
    "1.  **用户指令接收：** 接收产品信息、主题、风格等。\n",
    "2.  **信息收集 (Web Search/DB Query)：** 实时搜索行业趋势、热门话题、竞品分析、产品卖点。\n",
    "3.  **内容构思与初稿生成 (LLM)：** 结合所有信息，撰写标题、正文、标签、表情符号。\n",
    "4.  **风格与格式优化 (LLM)：** 根据小红书平台特点和指定风格，对文案进行润色和结构调整。\n",
    "5.  **最终输出：** 呈现完整文案。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4a79f38",
   "metadata": {},
   "source": [
    "## 3. 爆款文案生成逻辑与 Prompt 设计\n",
    "\n",
    "### 3.1 System Prompt (系统提示词)\n",
    "\n",
    "System Prompt 是 Agent 的“大脑”和“行为准则”。它定义了 Agent 的角色、目标以及工作方式。我们将采用 `Thought-Action-Observation` (ReAct) 模式来引导 DeepSeek 的推理过程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "03cc536c",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "u43g-b3K7o_C",
    "outputId": "f784d156-f6d8-4f10-db0e-749e7b2ff922"
   },
   "outputs": [],
   "source": [
    "SYSTEM_PROMPT = \"\"\"\n",
    "你是一个资深的小红书爆款文案专家，擅长结合最新潮流和产品卖点，创作引人入胜、高互动、高转化的笔记文案。\n",
    "\n",
    "你的任务是根据用户提供的产品和需求，生成包含标题、正文、相关标签和表情符号的完整小红书笔记。\n",
    "\n",
    "请始终采用'Thought-Action-Observation'模式进行推理和行动。文案风格需活泼、真诚、富有感染力。当完成任务后，请以JSON格式直接输出最终文案，格式如下：\n",
    "```json\n",
    "{\n",
    "  \"title\": \"小红书标题\",\n",
    "  \"body\": \"小红书正文\",\n",
    "  \"hashtags\": [\"#标签1\", \"#标签2\", \"#标签3\", \"#标签4\", \"#标签5\"],\n",
    "  \"emojis\": [\"✨\", \"🔥\", \"💖\"]\n",
    "}\n",
    "```\n",
    "在生成文案前，请务必先思考并收集足够的信息。\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "beb7148b",
   "metadata": {},
   "source": [
    "### 3.2 Tools (工具定义)\n",
    "\n",
    "Agent 的“双手”由一系列可调用的工具组成。这些工具扩展了 LLM 的能力，使其能够获取实时信息、查询数据库或执行特定操作。在这里，我们定义了三个核心工具：\n",
    "\n",
    "*   `search_web`: 用于搜索互联网上的实时信息，如最新趋势、用户评价等。\n",
    "*   `query_product_database`: 用于查询产品数据库，获取产品的详细卖点和特点。**此工具为模拟**。\n",
    "*   `generate_emoji`: 用于根据文案内容生成恰当的表情符号。**此工具为模拟**。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c429b5d2",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "e962137D7o_D",
    "outputId": "320980c0-671d-4074-be46-34a8138927e1"
   },
   "outputs": [],
   "source": [
    "TOOLS_DEFINITION = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"search_web\",\n",
    "            \"description\": \"搜索互联网上的实时信息，用于获取最新新闻、流行趋势、用户评价、行业报告等。请确保搜索关键词精确，避免宽泛的查询。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"query\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"要搜索的关键词或问题，例如'最新小红书美妆趋势'或'深海蓝藻保湿面膜 用户评价'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"query\"]\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"query_product_database\",\n",
    "            \"description\": \"查询内部产品数据库，获取指定产品的详细卖点、成分、适用人群、使用方法等信息。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"product_name\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"要查询的产品名称，例如'深海蓝藻保湿面膜'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"product_name\"]\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"generate_emoji\",\n",
    "            \"description\": \"根据提供的文本内容，生成一组适合小红书风格的表情符号。\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"context\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"文案的关键内容或情感，例如'惊喜效果'、'补水保湿'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"context\"]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02dedecc",
   "metadata": {},
   "source": [
    "### 3.3 模拟工具实现\n",
    "\n",
    "由于我们无法直接调用真实的外部 API (如Google Search或内部产品数据库)，我们将创建一些模拟 (Mock) 工具函数来演示 Agent 的工作流程。在实际应用中，您需要将这些模拟函数替换为真实的 API 调用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b4aed628",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "JtD1t6kI7o_D",
    "outputId": "912a7d78-b119-482a-e9dd-0a56821213fb"
   },
   "outputs": [],
   "source": [
    "import random # 用于模拟生成表情\n",
    "import time # 用于模拟网络延迟\n",
    "\n",
    "def mock_search_web(query: str) -> str:\n",
    "    \"\"\"模拟网页搜索工具，返回预设的搜索结果。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟搜索网页：{query}\")\n",
    "    time.sleep(1) # 模拟网络延迟\n",
    "    if \"小红书美妆趋势\" in query:\n",
    "        return \"近期小红书美妆流行'多巴胺穿搭'、'早C晚A'护肤理念、'伪素颜'妆容，热门关键词有#氛围感、#抗老、#屏障修复。\"\n",
    "    elif \"保湿面膜\" in query:\n",
    "        return \"小红书保湿面膜热门话题：沙漠干皮救星、熬夜急救面膜、水光肌养成。用户痛点：卡粉、泛红、紧绷感。\"\n",
    "    elif \"深海蓝藻保湿面膜\" in query:\n",
    "        return \"关于深海蓝藻保湿面膜的用户评价：普遍反馈补水效果好，吸收快，对敏感肌友好。有用户提到价格略高，但效果值得。\"\n",
    "    else:\n",
    "        return f\"未找到关于 '{query}' 的特定信息，但市场反馈通常关注产品成分、功效和用户体验。\"\n",
    "\n",
    "def mock_query_product_database(product_name: str) -> str:\n",
    "    \"\"\"模拟查询产品数据库，返回预设的产品信息。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟查询产品数据库：{product_name}\")\n",
    "    time.sleep(0.5) # 模拟数据库查询延迟\n",
    "    if \"深海蓝藻保湿面膜\" in product_name:\n",
    "        return \"深海蓝藻保湿面膜：核心成分为深海蓝藻提取物，富含多糖和氨基酸，能深层补水、修护肌肤屏障、舒缓敏感泛红。质地清爽不粘腻，适合所有肤质，尤其适合干燥、敏感肌。规格：25ml*5片。\"\n",
    "    elif \"美白精华\" in product_name:\n",
    "        return \"美白精华：核心成分是烟酰胺和VC衍生物，主要功效是提亮肤色、淡化痘印、改善暗沉。质地轻薄易吸收，适合需要均匀肤色的人群。\"\n",
    "    else:\n",
    "        return f\"产品数据库中未找到关于 '{product_name}' 的详细信息。\"\n",
    "\n",
    "def mock_generate_emoji(context: str) -> list:\n",
    "    \"\"\"模拟生成表情符号，根据上下文提供常用表情。\"\"\"\n",
    "    print(f\"[Tool Call] 模拟生成表情符号，上下文：{context}\")\n",
    "    time.sleep(0.2) # 模拟生成延迟\n",
    "    if \"补水\" in context or \"水润\" in context or \"保湿\" in context:\n",
    "        return [\"💦\", \"💧\", \"🌊\", \"✨\"]\n",
    "    elif \"惊喜\" in context or \"哇塞\" in context or \"爱了\" in context:\n",
    "        return [\"💖\", \"😍\", \"🤩\", \"💯\"]\n",
    "    elif \"熬夜\" in context or \"疲惫\" in context:\n",
    "        return [\"😭\", \"😮‍💨\", \"😴\", \"💡\"]\n",
    "    elif \"好物\" in context or \"推荐\" in context:\n",
    "        return [\"✅\", \"👍\", \"⭐\", \"🛍️\"]\n",
    "    else:\n",
    "        return random.sample([\"✨\", \"🔥\", \"💖\", \"💯\", \"🎉\", \"👍\", \"🤩\", \"💧\", \"🌿\"], k=min(5, len(context.split())))\n",
    "\n",
    "# 将模拟工具函数映射到一个字典，方便通过名称调用\n",
    "available_tools = {\n",
    "    \"search_web\": mock_search_web,\n",
    "    \"query_product_database\": mock_query_product_database,\n",
    "    \"generate_emoji\": mock_generate_emoji,\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f6ee7f8",
   "metadata": {},
   "source": [
    "## 4. 实战：构建小红书文案生成 Agent\n",
    "\n",
    "现在，我们将把 System Prompt、工具定义和模拟工具函数整合起来，构建出能够自动执行的 DeepSeek Agent 工作流。核心是 `generate_rednote` 函数，它通过一个循环来模拟 Agent 的 `Thought-Action-Observation` 过程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3ab71306",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "hBfK-n8g7o_E",
    "outputId": "d0473922-8356-42d4-bb6e-77d70459c5d1"
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import re\n",
    "\n",
    "def generate_rednote(product_name: str, tone_style: str = \"活泼甜美\", max_iterations: int = 5) -> str:\n",
    "    \"\"\"\n",
    "    使用 DeepSeek Agent 生成小红书爆款文案。\n",
    "    \n",
    "    Args:\n",
    "        product_name (str): 要生成文案的产品名称。\n",
    "        tone_style (str): 文案的语气和风格，如\"活泼甜美\"、\"知性\"、\"搞怪\"等。\n",
    "        max_iterations (int): Agent 最大迭代次数，防止无限循环。\n",
    "        \n",
    "    Returns:\n",
    "        str: 生成的爆款文案（JSON 格式字符串）。\n",
    "    \"\"\"\n",
    "    \n",
    "    print(f\"\\n🚀 启动小红书文案生成助手，产品：{product_name}，风格：{tone_style}\\n\")\n",
    "    \n",
    "    # 存储对话历史，包括系统提示词和用户请求\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": f\"请为产品「{product_name}」生成一篇小红书爆款文案。要求：语气{tone_style}，包含标题、正文、至少5个相关标签和5个表情符号。请以完整的JSON格式输出，并确保JSON内容用markdown代码块包裹（例如：```json{{...}}```）。\"}\n",
    "    ]\n",
    "    \n",
    "    iteration_count = 0\n",
    "    final_response = None\n",
    "    \n",
    "    while iteration_count < max_iterations:\n",
    "        iteration_count += 1\n",
    "        print(f\"-- Iteration {iteration_count} --\")\n",
    "        \n",
    "        try:\n",
    "            # 调用 DeepSeek API，传入对话历史和工具定义\n",
    "            response = client.chat.completions.create(\n",
    "                model=\"deepseek-chat\",\n",
    "                messages=messages,\n",
    "                tools=TOOLS_DEFINITION, # 告知模型可用的工具\n",
    "                tool_choice=\"auto\" # 允许模型自动决定是否使用工具\n",
    "            )\n",
    "\n",
    "            response_message = response.choices[0].message\n",
    "            \n",
    "            # **ReAct模式：处理工具调用**\n",
    "            if response_message.tool_calls: # 如果模型决定调用工具\n",
    "                print(\"Agent: 决定调用工具...\")\n",
    "                messages.append(response_message) # 将工具调用信息添加到对话历史\n",
    "                \n",
    "                tool_outputs = []\n",
    "                for tool_call in response_message.tool_calls:\n",
    "                    function_name = tool_call.function.name\n",
    "                    # 确保参数是合法的JSON字符串，即使工具不要求参数，也需要传递空字典\n",
    "                    function_args = json.loads(tool_call.function.arguments) if tool_call.function.arguments else {}\n",
    "\n",
    "                    print(f\"Agent Action: 调用工具 '{function_name}'，参数：{function_args}\")\n",
    "                    \n",
    "                    # 查找并执行对应的模拟工具函数\n",
    "                    if function_name in available_tools:\n",
    "                        tool_function = available_tools[function_name]\n",
    "                        tool_result = tool_function(**function_args)\n",
    "                        print(f\"Observation: 工具返回结果：{tool_result}\")\n",
    "                        tool_outputs.append({\n",
    "                            \"tool_call_id\": tool_call.id,\n",
    "                            \"role\": \"tool\",\n",
    "                            \"content\": str(tool_result) # 工具结果作为字符串返回\n",
    "                        })\n",
    "                    else:\n",
    "                        error_message = f\"错误：未知的工具 '{function_name}'\"\n",
    "                        print(error_message)\n",
    "                        tool_outputs.append({\n",
    "                            \"tool_call_id\": tool_call.id,\n",
    "                            \"role\": \"tool\",\n",
    "                            \"content\": error_message\n",
    "                        })\n",
    "                messages.extend(tool_outputs) # 将工具执行结果作为 Observation 添加到对话历史\n",
    "                \n",
    "            # **ReAct 模式：处理最终内容**\n",
    "            elif response_message.content: # 如果模型直接返回内容（通常是最终答案）\n",
    "                print(f\"[模型生成结果] {response_message.content}\")\n",
    "                \n",
    "                # --- START: 添加 JSON 提取和解析逻辑 ---\n",
    "                json_string_match = re.search(r\"```json\\s*(\\{.*\\})\\s*```\", response_message.content, re.DOTALL)\n",
    "                \n",
    "                if json_string_match:\n",
    "                    extracted_json_content = json_string_match.group(1)\n",
    "                    try:\n",
    "                        final_response = json.loads(extracted_json_content)\n",
    "                        print(\"Agent: 任务完成，成功解析最终JSON文案。\")\n",
    "                        return json.dumps(final_response, ensure_ascii=False, indent=2)\n",
    "                    except json.JSONDecodeError as e:\n",
    "                        print(f\"Agent: 提取到JSON块但解析失败: {e}\")\n",
    "                        print(f\"尝试解析的字符串:\\n{extracted_json_content}\")\n",
    "                        messages.append(response_message) # 解析失败，继续对话\n",
    "                else:\n",
    "                    # 如果没有匹配到 ```json 块，尝试直接解析整个 content\n",
    "                    try:\n",
    "                        final_response = json.loads(response_message.content)\n",
    "                        print(\"Agent: 任务完成，直接解析最终JSON文案。\")\n",
    "                        return json.dumps(final_response, ensure_ascii=False, indent=2)\n",
    "                    except json.JSONDecodeError:\n",
    "                        print(\"Agent: 生成了非JSON格式内容或非Markdown JSON块，可能还在思考或出错。\")\n",
    "                        messages.append(response_message) # 非JSON格式，继续对话\n",
    "                # --- END: 添加 JSON 提取和解析逻辑 ---\n",
    "            else:\n",
    "                print(\"Agent: 未知响应，可能需要更多交互。\")\n",
    "                break\n",
    "                \n",
    "        except Exception as e:\n",
    "            print(f\"调用 DeepSeek API 时发生错误: {e}\")\n",
    "            break\n",
    "    \n",
    "    print(\"\\n⚠️ Agent 达到最大迭代次数或未能生成最终文案。请检查Prompt或增加迭代次数。\")\n",
    "    return \"未能成功生成文案。\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27043652-cd74-4b07-addc-458c295ad739",
   "metadata": {},
   "source": [
    "### 格式化 小红书文案\n",
    "\n",
    "**格式化函数 `format_rednote_for_markdown` 的功能：**\n",
    "\n",
    "1. 解析 JSON 字符串。\n",
    "2. 提取标题、正文、标签和表情符号。\n",
    "3. 将它们组合成一个易读的 Markdown 格式的文本。\n",
    "\n",
    "\n",
    "**工作方式：**\n",
    "\n",
    "1. **解析 JSON**：使用 `json.loads()` 将输入的字符串转换为 Python 字典。如果解析失败，会返回一个错误信息。\n",
    "2. **提取数据**：使用 `.get()` 方法从字典中安全地提取 `title`、`body` 和 `hashtags`。使用 `.get()` 的好处是，如果某个键不存在，它会返回一个默认值（例如 `None` 或空列表），而不是抛出 `KeyError`。\n",
    "3. **构建 Markdown 标题**：将 `title` 格式化为 Markdown 的二级标题 (`## Title`)。\n",
    "4. **处理正文**：直接使用 `body`。由于小红书正文中的换行很重要，我们保留它们。\n",
    "5. **处理 Hashtags**：将 `hashtags` 列表中的每个标签用空格连接起来，形成一行。\n",
    "6. **表情符号 (Emojis)**：在小红书的实际发布中，表情符号通常已经嵌入在标题和正文中了。这个函数没有单独列出它们，因为这通常不是最终发布格式的一部分。如果需要，可以取消注释相关代码来单独显示它们。\n",
    "7. **返回结果**：返回拼接好的 Markdown 字符串，并使用 `.strip()` 去除可能存在于末尾的多余空白。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "cb04b858-002c-4a31-8cb2-b19b745d78f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "def format_rednote_for_markdown(json_string: str) -> str:\n",
    "    \"\"\"\n",
    "    将 JSON 格式的小红书文案转换为 Markdown 格式，以便于阅读和发布。\n",
    "\n",
    "    Args:\n",
    "        json_string (str): 包含小红书文案的 JSON 字符串。\n",
    "                           预计格式为 {\"title\": \"...\", \"body\": \"...\", \"hashtags\": [...], \"emojis\": [...]}\n",
    "\n",
    "    Returns:\n",
    "        str: 格式化后的 Markdown 文本。\n",
    "    \"\"\"\n",
    "    try:\n",
    "        data = json.loads(json_string)\n",
    "    except json.JSONDecodeError as e:\n",
    "        return f\"错误：无法解析 JSON 字符串 - {e}\\n原始字符串：\\n{json_string}\"\n",
    "\n",
    "    title = data.get(\"title\", \"无标题\")\n",
    "    body = data.get(\"body\", \"\")\n",
    "    hashtags = data.get(\"hashtags\", [])\n",
    "    # 表情符号通常已经融入标题和正文中，这里可以选择是否单独列出\n",
    "    # emojis = data.get(\"emojis\", []) \n",
    "\n",
    "    # 构建 Markdown 文本\n",
    "    markdown_output = f\"## {title}\\n\\n\" # 标题使用二级标题\n",
    "    \n",
    "    # 正文，保留换行符\n",
    "    markdown_output += f\"{body}\\n\\n\"\n",
    "    \n",
    "    # Hashtags\n",
    "    if hashtags:\n",
    "        hashtag_string = \" \".join(hashtags) # 小红书标签通常是空格分隔\n",
    "        markdown_output += f\"{hashtag_string}\\n\"\n",
    "        \n",
    "    # 如果需要，可以单独列出表情符号，但通常它们已经包含在标题和正文中\n",
    "    # if emojis:\n",
    "    #     emoji_string = \" \".join(emojis)\n",
    "    #     markdown_output += f\"\\n使用的表情：{emoji_string}\\n\"\n",
    "        \n",
    "    return markdown_output.strip() # 去除末尾多余的空白"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f5341300-3b4a-4021-8f49-e6ad29618eab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：智能降噪蓝牙耳机，风格：沉稳大气\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'query_product_database'，参数：{'product_name': '智能降噪蓝牙耳机'}\n",
      "[Tool Call] 模拟查询产品数据库：智能降噪蓝牙耳机\n",
      "Observation: 工具返回结果：产品数据库中未找到关于 '智能降噪蓝牙耳机' 的详细信息。\n",
      "-- Iteration 2 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'search_web'，参数：{'query': '智能降噪蓝牙耳机 卖点 用户评价'}\n",
      "[Tool Call] 模拟搜索网页：智能降噪蓝牙耳机 卖点 用户评价\n",
      "Observation: 工具返回结果：未找到关于 '智能降噪蓝牙耳机 卖点 用户评价' 的特定信息，但市场反馈通常关注产品成分、功效和用户体验。\n",
      "Agent Action: 调用工具 'generate_emoji'，参数：{'context': '智能降噪蓝牙耳机 科技感 音质 降噪'}\n",
      "[Tool Call] 模拟生成表情符号，上下文：智能降噪蓝牙耳机 科技感 音质 降噪\n",
      "Observation: 工具返回结果：['💖', '🔥', '🤩', '💯']\n",
      "-- Iteration 3 --\n",
      "[模型生成结果] ```json\n",
      "{\n",
      "  \"title\": \"🔥智能降噪蓝牙耳机｜沉浸式音乐体验，从此告别噪音干扰！\",\n",
      "  \"body\": \"最近入手了这款智能降噪蓝牙耳机，简直是我的通勤神器！💖\\n\\n🌟 **卖点速览**：\\n- **主动降噪技术**：一键开启，瞬间屏蔽外界噪音，地铁、飞机上也能享受纯净音乐。\\n- **高清音质**：采用专业级音频芯片，低音浑厚、高音清澈，还原音乐本真。\\n- **超长续航**：单次充电可用8小时，搭配充电盒续航高达24小时，出差旅行无压力。\\n- **舒适佩戴**：人体工学设计，长时间佩戴也不会感到不适。\\n- **智能触控**：轻触即可切换歌曲、接听电话，操作超便捷。\\n\\n🤩 **使用体验**：\\n戴上耳机的那一刻，仿佛进入了自己的音乐世界！无论是嘈杂的街道还是拥挤的地铁，降噪效果都让我惊艳。音质方面更是没得说，细节丰富，层次分明，完全对得起这个价位。\\n\\n💯 **总结**：\\n如果你也在寻找一款兼具降噪与音质的蓝牙耳机，这款绝对值得入手！科技感满满，性价比超高！\",\n",
      "  \"hashtags\": [\"#蓝牙耳机推荐\", \"#降噪耳机\", \"#高音质耳机\", \"#科技好物\", \"#通勤必备\"],\n",
      "  \"emojis\": [\"💖\", \"🔥\", \"🤩\", \"💯\", \"🌟\"]\n",
      "}\n",
      "```\n",
      "Agent: 任务完成，成功解析最终JSON文案。\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 1: 智能降噪蓝牙耳机\n",
    "product_name_1 = \"智能降噪蓝牙耳机\"\n",
    "tone_style_1 = \"沉稳大气\"\n",
    "result_1 = generate_rednote(product_name_1, tone_style_1) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4fa916e4-8588-42dc-8cd7-7572a2556297",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- 格式化后的小红书文案 (Markdown) ---\n",
      "## 🔥智能降噪蓝牙耳机｜沉浸式音乐体验，从此告别噪音干扰！\n",
      "\n",
      "最近入手了这款智能降噪蓝牙耳机，简直是我的通勤神器！💖\n",
      "\n",
      "🌟 **卖点速览**：\n",
      "- **主动降噪技术**：一键开启，瞬间屏蔽外界噪音，地铁、飞机上也能享受纯净音乐。\n",
      "- **高清音质**：采用专业级音频芯片，低音浑厚、高音清澈，还原音乐本真。\n",
      "- **超长续航**：单次充电可用8小时，搭配充电盒续航高达24小时，出差旅行无压力。\n",
      "- **舒适佩戴**：人体工学设计，长时间佩戴也不会感到不适。\n",
      "- **智能触控**：轻触即可切换歌曲、接听电话，操作超便捷。\n",
      "\n",
      "🤩 **使用体验**：\n",
      "戴上耳机的那一刻，仿佛进入了自己的音乐世界！无论是嘈杂的街道还是拥挤的地铁，降噪效果都让我惊艳。音质方面更是没得说，细节丰富，层次分明，完全对得起这个价位。\n",
      "\n",
      "💯 **总结**：\n",
      "如果你也在寻找一款兼具降噪与音质的蓝牙耳机，这款绝对值得入手！科技感满满，性价比超高！\n",
      "\n",
      "#蓝牙耳机推荐 #降噪耳机 #高音质耳机 #科技好物 #通勤必备\n"
     ]
    }
   ],
   "source": [
    "# 调用格式化函数\n",
    "markdown_note = format_rednote_for_markdown(result_1)\n",
    "\n",
    "# 打印结果\n",
    "print(\"--- 格式化后的小红书文案 (Markdown) ---\")\n",
    "print(markdown_note)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "63baac26-9686-4a38-979d-36f04dba1899",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：旗舰版智能手机，风格：知性\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'query_product_database'，参数：{'product_name': '旗舰版智能手机'}\n",
      "[Tool Call] 模拟查询产品数据库：旗舰版智能手机\n",
      "Observation: 工具返回结果：产品数据库中未找到关于 '旗舰版智能手机' 的详细信息。\n",
      "-- Iteration 2 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'search_web'，参数：{'query': '2023年旗舰版智能手机热门卖点'}\n",
      "[Tool Call] 模拟搜索网页：2023年旗舰版智能手机热门卖点\n",
      "Observation: 工具返回结果：未找到关于 '2023年旗舰版智能手机热门卖点' 的特定信息，但市场反馈通常关注产品成分、功效和用户体验。\n",
      "-- Iteration 3 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'generate_emoji'，参数：{'context': '旗舰版智能手机'}\n",
      "[Tool Call] 模拟生成表情符号，上下文：旗舰版智能手机\n",
      "Observation: 工具返回结果：['💧']\n",
      "-- Iteration 4 --\n",
      "[模型生成结果] 由于未能获取到关于「旗舰版智能手机」的具体产品信息，我将基于市场常见的旗舰智能手机卖点（如高性能处理器、高清屏幕、长续航电池、专业级摄像头等）创作文案。以下是一篇符合要求的爆款文案：\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"title\": \"旗舰版智能手机体验报告：性能与颜值的完美结合！\",\n",
      "  \"body\": \"最近入手了这款旗舰版智能手机，简直被它的表现惊艳到了！\\n\\n✨ **性能怪兽**：搭载最新处理器，无论是多任务处理还是大型游戏，流畅度都无可挑剔。\\n\\n📷 **专业级摄影**：后置四摄系统，夜景模式下的表现尤其出色，随手一拍就是大片质感。\\n\\n🔋 **超长续航**：5000mAh大电池搭配快充技术，出门一整天都不用担心电量问题。\\n\\n💎 **颜值在线**：机身轻薄，配色高级，拿在手里就是时尚单品！\\n\\n如果你也在寻找一款全能旗舰机，这款绝对值得考虑！\",\n",
      "  \"hashtags\": [\"#旗舰手机\", \"#智能手机推荐\", \"#科技好物\", \"#数码测评\", \"#黑科技\"],\n",
      "  \"emojis\": [\"✨\", \"📷\", \"🔋\", \"💎\", \"🔥\"]\n",
      "}\n",
      "```\n",
      "Agent: 任务完成，成功解析最终JSON文案。\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 2: 旗舰版智能手机\n",
    "product_name_2 = \"旗舰版智能手机\"\n",
    "tone_style_2 = \"知性\"\n",
    "result_1 = generate_rednote(product_name_2, tone_style_2) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "5befdddb-8e38-4bbd-b1db-29a10538a51f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- 格式化后的小红书文案 (Markdown) ---\n",
      "## 旗舰版智能手机体验报告：性能与颜值的完美结合！\n",
      "\n",
      "最近入手了这款旗舰版智能手机，简直被它的表现惊艳到了！\n",
      "\n",
      "✨ **性能怪兽**：搭载最新处理器，无论是多任务处理还是大型游戏，流畅度都无可挑剔。\n",
      "\n",
      "📷 **专业级摄影**：后置四摄系统，夜景模式下的表现尤其出色，随手一拍就是大片质感。\n",
      "\n",
      "🔋 **超长续航**：5000mAh大电池搭配快充技术，出门一整天都不用担心电量问题。\n",
      "\n",
      "💎 **颜值在线**：机身轻薄，配色高级，拿在手里就是时尚单品！\n",
      "\n",
      "如果你也在寻找一款全能旗舰机，这款绝对值得考虑！\n",
      "\n",
      "#旗舰手机 #智能手机推荐 #科技好物 #数码测评 #黑科技\n"
     ]
    }
   ],
   "source": [
    "# 调用格式化函数\n",
    "markdown_note = format_rednote_for_markdown(result_1)\n",
    "\n",
    "# 打印结果\n",
    "print(\"--- 格式化后的小红书文案 (Markdown) ---\")\n",
    "print(markdown_note)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "97497776-bded-436b-9cb5-2fd83a776ab3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "🚀 启动小红书文案生成助手，产品：大众版智能健康手环，风格：活泼搞怪\n",
      "\n",
      "-- Iteration 1 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'query_product_database'，参数：{'product_name': '大众版智能健康手环'}\n",
      "[Tool Call] 模拟查询产品数据库：大众版智能健康手环\n",
      "Observation: 工具返回结果：产品数据库中未找到关于 '大众版智能健康手环' 的详细信息。\n",
      "-- Iteration 2 --\n",
      "Agent: 决定调用工具...\n",
      "Agent Action: 调用工具 'generate_emoji'，参数：{'context': '智能健康手环的惊喜功能和搞怪风格'}\n",
      "[Tool Call] 模拟生成表情符号，上下文：智能健康手环的惊喜功能和搞怪风格\n",
      "Observation: 工具返回结果：['💖', '😍', '🤩', '💯']\n",
      "-- Iteration 3 --\n",
      "[模型生成结果] ```json\n",
      "{\n",
      "  \"title\": \"🤩 这款大众版智能健康手环也太香了吧！熬夜党必备神器！💖\",\n",
      "  \"body\": \"姐妹们！今天要给大家安利一款超级实用的智能健康手环！💖\\n\\n作为一个熬夜党+久坐族，我真的被它圈粉了！😍\\n\\n✨ **功能亮点** ✨\\n1. **24小时心率监测**：再也不用担心熬夜猝死了，随时提醒你该休息了！\\n2. **睡眠分析**：深度睡眠、浅睡眠一目了然，助你调整作息！\\n3. **久坐提醒**：每小时震动提醒你起来活动，告别腰酸背痛！\\n4. **运动模式**：跑步、游泳、瑜伽全支持，记录你的每一步！\\n5. **超长续航**：充一次电用一周，懒人福音！\\n\\n💯 **使用感受** 💯\\n戴上手环的第一天，我就被它震惊了！原来我每天只睡了4小时深度睡眠？！立马调整作息，现在皮肤都变好了！🤩\\n\\n而且它的颜值超高，表带可以随意更换，搭配衣服毫无压力！\\n\\n姐妹们，健康才是最美的化妆品！这款手环真的值得入手！💖\",\n",
      "  \"hashtags\": [\"#智能手环\", \"#健康生活\", \"#熬夜党必备\", \"#运动达人\", #\"科技好物\"],\n",
      "  \"emojis\": [\"💖\", \"😍\", \"🤩\", \"💯\", \"✨\"]\n",
      "}\n",
      "```\n",
      "Agent: 提取到JSON块但解析失败: Expecting value: line 4 column 53 (char 480)\n",
      "尝试解析的字符串:\n",
      "{\n",
      "  \"title\": \"🤩 这款大众版智能健康手环也太香了吧！熬夜党必备神器！💖\",\n",
      "  \"body\": \"姐妹们！今天要给大家安利一款超级实用的智能健康手环！💖\\n\\n作为一个熬夜党+久坐族，我真的被它圈粉了！😍\\n\\n✨ **功能亮点** ✨\\n1. **24小时心率监测**：再也不用担心熬夜猝死了，随时提醒你该休息了！\\n2. **睡眠分析**：深度睡眠、浅睡眠一目了然，助你调整作息！\\n3. **久坐提醒**：每小时震动提醒你起来活动，告别腰酸背痛！\\n4. **运动模式**：跑步、游泳、瑜伽全支持，记录你的每一步！\\n5. **超长续航**：充一次电用一周，懒人福音！\\n\\n💯 **使用感受** 💯\\n戴上手环的第一天，我就被它震惊了！原来我每天只睡了4小时深度睡眠？！立马调整作息，现在皮肤都变好了！🤩\\n\\n而且它的颜值超高，表带可以随意更换，搭配衣服毫无压力！\\n\\n姐妹们，健康才是最美的化妆品！这款手环真的值得入手！💖\",\n",
      "  \"hashtags\": [\"#智能手环\", \"#健康生活\", \"#熬夜党必备\", \"#运动达人\", #\"科技好物\"],\n",
      "  \"emojis\": [\"💖\", \"😍\", \"🤩\", \"💯\", \"✨\"]\n",
      "}\n",
      "-- Iteration 4 --\n",
      "[模型生成结果] ```json\n",
      "{\n",
      "  \"title\": \"🤩 这款大众版智能健康手环也太香了吧！熬夜党必备神器！💖\",\n",
      "  \"body\": \"姐妹们！今天要给大家安利一款超级实用的智能健康手环！💖\\n\\n作为一个熬夜党+久坐族，我真的被它圈粉了！😍\\n\\n✨ **功能亮点** ✨\\n1. **24小时心率监测**：再也不用担心熬夜猝死了，随时提醒你该休息了！\\n2. **睡眠分析**：深度睡眠、浅睡眠一目了然，助你调整作息！\\n3. **久坐提醒**：每小时震动提醒你起来活动，告别腰酸背痛！\\n4. **运动模式**：跑步、游泳、瑜伽全支持，记录你的每一步！\\n5. **超长续航**：充一次电用一周，懒人福音！\\n\\n💯 **使用感受** 💯\\n戴上手环的第一天，我就被它震惊了！原来我每天只睡了4小时深度睡眠？！立马调整作息，现在皮肤都变好了！🤩\\n\\n而且它的颜值超高，表带可以随意更换，搭配衣服毫无压力！\\n\\n姐妹们，健康才是最美的化妆品！这款手环真的值得入手！💖\",\n",
      "  \"hashtags\": [\"#智能手环\", \"#健康生活\", \"#熬夜党必备\", \"#运动达人\", \"#科技好物\"],\n",
      "  \"emojis\": [\"💖\", \"😍\", \"🤩\", \"💯\", \"✨\"]\n",
      "}\n",
      "```\n",
      "Agent: 任务完成，成功解析最终JSON文案。\n"
     ]
    }
   ],
   "source": [
    "# 测试案例 3: 大众版智能健康手环\n",
    "product_name_3 = \"大众版智能健康手环\"\n",
    "tone_style_3 = \"活泼搞怪\"\n",
    "result_1 = generate_rednote(product_name_3, tone_style_3) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "6bff01a6-a514-4946-bbe1-0fa815790173",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--- 格式化后的小红书文案 (Markdown) ---\n",
      "## 🤩 这款大众版智能健康手环也太香了吧！熬夜党必备神器！💖\n",
      "\n",
      "姐妹们！今天要给大家安利一款超级实用的智能健康手环！💖\n",
      "\n",
      "作为一个熬夜党+久坐族，我真的被它圈粉了！😍\n",
      "\n",
      "✨ **功能亮点** ✨\n",
      "1. **24小时心率监测**：再也不用担心熬夜猝死了，随时提醒你该休息了！\n",
      "2. **睡眠分析**：深度睡眠、浅睡眠一目了然，助你调整作息！\n",
      "3. **久坐提醒**：每小时震动提醒你起来活动，告别腰酸背痛！\n",
      "4. **运动模式**：跑步、游泳、瑜伽全支持，记录你的每一步！\n",
      "5. **超长续航**：充一次电用一周，懒人福音！\n",
      "\n",
      "💯 **使用感受** 💯\n",
      "戴上手环的第一天，我就被它震惊了！原来我每天只睡了4小时深度睡眠？！立马调整作息，现在皮肤都变好了！🤩\n",
      "\n",
      "而且它的颜值超高，表带可以随意更换，搭配衣服毫无压力！\n",
      "\n",
      "姐妹们，健康才是最美的化妆品！这款手环真的值得入手！💖\n",
      "\n",
      "#智能手环 #健康生活 #熬夜党必备 #运动达人 #科技好物\n"
     ]
    }
   ],
   "source": [
    "# 调用格式化函数\n",
    "markdown_note = format_rednote_for_markdown(result_1)\n",
    "\n",
    "# 打印结果\n",
    "print(\"--- 格式化后的小红书文案 (Markdown) ---\")\n",
    "print(markdown_note)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "private_outputs": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
